<?php
namespace app\home\controller;

use think\Controller;
use think\Db;
use think\Exception;

class Help extends Controller{
    public function applyHelp() //请求帮助接口
    {
        return $this->fetch('help/applyHelp');
    }

    public function toVolunJson()    //可发件人信息接口
    {
        $toMail=[];

        //各院青协
        $College=db("college")->select();
        foreach ($College as $key=>$item)
        {
            $College[$key]["username"]=$College[$key]["college_name"]."-青协";

            $College[$key]["name"]=$College[$key]["college_name"]."-青协";
        }
        $toMail[]=[
            "type"=>"以下学院青协成员",
            "data"=>$College
        ];

        //所有青协成员信息
        $AllVolu=db("users")->field('username,name,college,major,department')->where('auth','<>',0)->select();
        $toMail[]=[
            "type"=>"青协成员",
            "data"=>$AllVolu
        ];

        return json($toMail);
    }

    public function SendtoVolun()   //发送求助
    {
        $input=input('post.');
        $title=$input["title"];
        $content=$input["content"];

        //将发送的邮件存储到数据库
        $SafeCode=cookie('SafeCode');
        $PersonData=Db::name('users')->where('SafeCode',$SafeCode)->find();
        $fromUser=$PersonData["name"];
        $uid=$PersonData["Id"];
        $randCode=GetRandStr(20);   //获取随机码

        $count=\db('message')
            ->group('code')
            ->where('uid',$uid)
            ->whereTime('time','>=',date('Y-m-d'))
            ->whereTime('time','<',date('Y-m-d',time()+24*3600))
            ->count();

        if ($count>=C('limit_msg')  && in_array($PersonData['auth'],[5,0]))
            return json(["msg"=>"每日只能发送".C('limit_msg')."条信息"]);


        $MsgId=Db::name('message')->insertGetId([
            'title'=>$title,
            'content'=>$content,
            'fromUser'=>$fromUser,
            'time'=>date('Y-m-d H:i:s',time()),
            'qq'=>$PersonData["qq"],
            //20210725 新增加入用户id
            'uid'=>$PersonData["Id"],
            'code'=>$randCode
        ]);


        $User=[];
        foreach ($input["toMail"] as $toMail)   //将发送人名单转化成每个用户的用户名
        {
            if(strstr($toMail,"-"))
            {
                $College=explode("-",$toMail);
                $CollegeData=$College[0];   //学院
                $Range=$College[1];         //发送人类别
                switch ($CollegeData)
                {
                    case "全体":
                        $SQL=db('users');
                        break;
                    default:
                        $SQL=db('users')->where("college",$CollegeData);
                }
                switch ($Range)
                {
                    case "全体":
                        $UserData=$SQL->select();
                        break;
                    case "青协":
                        $UserData=$SQL->where('auth','<>',0)->select();
                        break;
                }
                foreach ($UserData as $UserDatum)
                {
                    $User[]=$UserDatum["username"];
                }
            }else{
                if(!in_array($toMail,$User))
                    $User[]=$toMail;
            }
        }
        $content=$content."<br><br><br>".
            "\n请求人信息：<br>\n".
            "<p>用户名：".$fromUser."</p>\n".
            "<p>QQ:".$PersonData["qq"]."</p>\n".
            "<p>电话：".$PersonData['phone']."</p>\n".
            "<p>学院：".$PersonData["college"]."</p>\n".
            "<p>专业：".$PersonData["major"]."</p>\n";
        $success=0;
        $error=0;
        foreach ($User as $usernamme)   //发件
        {
            $UserData=Db::name('users')->where('username',$usernamme)->find();
            if($UserData)
            {
                try {
                    \db('message_queue')->insert([
                        'qq'=>$UserData["qq"],
                        'name'=>$UserData["name"],
                        'title'=>$title,
                        'content'=>$content,
                        'message_id'=>$MsgId,
                        'uid'=>$UserData['Id']
                    ]);
                    //send_mail($UserData["qq"]."@qq.com",$UserData["name"],$title,$content);
                    db('msg_read')->insert([
                        'message_id'=>$MsgId,
                        'read'=>false,
                        'uid'=>$UserData["Id"]
                    ]);
                }catch (Exception $e){
                    $error++;
                }
                $success++;
            }else{
                $error++;
            }
        }

        Monitor('使用了求助功能');

        return json(["msg"=>"请求完成，已加入消息队列"]);
    }
}